package com.egg.common.mybatis.config;


import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.egg.common.mybatis.interceptor.DataScopeInterceptor;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author east
 * @Description: mybatis-plus配置文件
 */
// 指定要扫描的Mapper类的包的路径
@MapperScan(value = "com.egg.**.mapper", annotationClass = Mapper.class)
@Configuration
public class MybatisPlusConfig {


    @Autowired
    private DataSource dataSource;


    /**
     * mybatis-plus分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        // 数据权限插件
        interceptor.addInnerInterceptor(new DataScopeInterceptor());
        return interceptor;
    }

    @Bean
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() throws IOException {
        MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
        mybatisPlus.setDataSource(dataSource);
        mybatisPlus.setPlugins(mybatisPlusInterceptor());
        mybatisPlus.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("**/*.xml"));
        MybatisConfiguration mc = new MybatisConfiguration();
        //mybatis-plus查询驼峰问题
        mc.setMapUnderscoreToCamelCase(true);
        // 自定义日志打印
        //mc.setLogImpl(MybatisLogConfig.class);
        mybatisPlus.setConfiguration(mc);
        return mybatisPlus;
    }

}
